package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
       //获取日期集合
       List<LocalDate> dateList = new ArrayList<>();
        LocalDate newEnd = end.plusDays(1);
        while (!(begin.equals(newEnd))){
           dateList.add(begin);
          begin = begin.plusDays(1);
       }

       List<Double> turnoverList = new ArrayList<>();
       //获取每天的营业额
        for (LocalDate date : dateList) {
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            LocalDateTime startTime = LocalDateTime.of(date, LocalTime.MIN);

            //将查询条件封装起来  注意平时我们是用对象传的，使用集合还需要遍历
            Map map  = new HashMap();
            map.put("begin",startTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //从数据库查询
            Double turnover = orderMapper.getTurnoverStatistics(map);
            //防止某天的营业额为空
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

       //转换日期集合,营业额集合内的数据类型
        String dateResultList = StringUtils.join(dateList, ",");
        String turnoverResultList = StringUtils.join(turnoverList, ",");

        return TurnoverReportVO
                .builder()
                .dateList(dateResultList)
                .turnoverList(turnoverResultList)
                .build();
    }

    /**
     * 用户数据统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        //获取天数日期
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }


        //两个集合存储数据
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList  = new ArrayList<>();
        for (LocalDate dayDate : dateList) {
            //封装查询数据
            LocalDateTime startTime = LocalDateTime.of(dayDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(dayDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",startTime);
            map.put("end",endTime);
            //获取每天的新增用户 select count(id) from user where create_time>? and create_time<?
            Integer dayNewUser = orderMapper.getDayNewUser(map);
            //获取截止到每天总共的用户量select count(id) from user where create_time <?
            Integer totalUser = orderMapper.getTotalUser(map);

            //健壮性判断
            dayNewUser = dayNewUser == null ? 0 : dayNewUser;
            totalUser = totalUser == null ? 0 : totalUser;

            //将数据添加到集合中
            newUserList.add(dayNewUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //获取日期列表
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.equals(end.plusDays(1))){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        //两个集合封装数据
        List<Integer> dayOrdersList = new ArrayList<>();
        List<Integer> dayValidOrdersList = new ArrayList<>();

        //两个变量记录订单总数、有效订单数
        Integer dayOrdersTotal = 0;
        Integer dayValidOrdersTotal = 0;

        for (LocalDate dayDate : dateList) {
            LocalDateTime startTime = LocalDateTime.of(dayDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(dayDate, LocalTime.MAX);
            //封装查询参数
            Map map = new HashMap();
            map.put("begin",startTime);
            map.put("end",endTime);
            //查询每日订单数列表 select count(id) from order where ordertime >? and ordertime <?
            Integer dayOrders = orderMapper.getDayOrders(map);
            //查询每日有效订单数列表select count(id) from order where ordertime >? and ordertime <? and status = orders.5完成
            map.put("status",Orders.COMPLETED);
            Integer dayValidOrders = orderMapper.getDayOrders(map);

            dayOrders = dayOrders == null ? 0 : dayOrders;
            dayValidOrders = dayValidOrders == null ? 0 : dayValidOrders;

            //记录总数
            dayOrdersTotal = dayOrdersTotal + dayOrders;
            dayValidOrdersTotal = dayValidOrdersTotal + dayValidOrders;

            //将数据添加到集合中
            dayOrdersList.add(dayOrders);
            dayValidOrdersList.add(dayValidOrders);
        }

        //计算订单完成率    健全性判断
        double orderCompletionRate = 0.0;
        if (dayOrdersTotal != 0){
            //整数进行浮点运算时，先将数据转化，如果是对结果进行转换，可能会失效
            orderCompletionRate = ((double) dayValidOrdersTotal) / dayOrdersTotal;
        }

        /**
         * 记录总数功能拿到外面来写，一个循环只干一件事
         * 利用Stream流里面的reduce()合并数据，在方法引用调用Interge的sum方法，最后在利用stream提供的get得到数据
         *       reduce是一种stream中的聚合操作，聚合的含义就是将多个值经过特定计算之后得到单个值，
         *       常见的 count 、sum 、avg 、max 、min 等函数就是一种聚合操作。
         * Integer dayOrdersTotal = dayOrdersList.stream().reduce(Integer::sum).get();
         * Integer dayValidOrdersTotal = dayValidOrdersList.stream().reduce(Integer::sum).get();
         */


        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(dayOrdersList,","))
                .totalOrderCount(dayOrdersTotal)
                .validOrderCount(dayValidOrdersTotal)
                .validOrderCountList(StringUtils.join(dayValidOrdersList,","))
                .build();
    }

    /**
     * 销量TOP10统计
     * @return
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {

            //封装查询参数
            Map map = new HashMap();
            map.put("begin",LocalDateTime.of(begin,LocalTime.MIN));
            map.put("end",LocalDateTime.of(end,LocalTime.MAX));
            //查询销量top10
            List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(map);
            List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
            List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
            //将数据封装到VO中
            String nameList = StringUtils.join(names,",");
            String numberList =StringUtils.join(numbers,",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }



    /**导出近30天的运营数据报表
     * @param response
     **/
    public void exportBusinessData(HttpServletResponse response) {
        //30天前
        LocalDate begin = LocalDate.now().minusDays(30);
        //昨天
        LocalDate end = LocalDate.now().minusDays(1);

        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
